package com.abner.basis.sync;

/**
 * 线程之间进行通信
 * 两个线程操作同一个变量,对变量进行加减操作
 *
 * @Author yuhui
 * @Date: 2024/3/19
 */
public class ThreadComm {

    public static void main(String[] args) {
        Share share = new Share();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "D").start();
    }
}

class Share {
    private int num = 0;

    /**
     * 加1
     */
    public synchronized void incr() throws InterruptedException {
        while (num != 0) {
            this.wait();
        }
        num++;
        System.out.println(Thread.currentThread().getName() + "进行加1操作,计算后的结果为: " + num);
        this.notifyAll();
    }

    /**
     * 减1
     */
    public synchronized void decr() throws InterruptedException {
       while (num != 1) {
           this.wait();
       }
        num--;
        System.out.println(Thread.currentThread().getName() + "进行减1操作,计算后的结果为: " + num);
        this.notifyAll();
    }

}
